using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.ProcessManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ProcessManagements;

namespace RBAC.Write.Api.Application.Handler.ProcessManagements
{
    /// <summary>
    /// 编辑工序分类 处理器
    /// </summary>
    public class UpdateProcessClassificationHandler : IRequestHandler<UpdateProcessClassificationCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ProcessClassification> repository;
        private readonly ILogger<UpdateProcessClassificationHandler> logger;

        public UpdateProcessClassificationHandler(
            IBaseRepository<ProcessClassification> repository,
            ILogger<UpdateProcessClassificationHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(UpdateProcessClassificationCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<int>();
            try
            {
                if (request.Id <= 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "无效的ID";
                    return Task.FromResult(res);
                }
                if (string.IsNullOrWhiteSpace(request.ClassificationCode))
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "工序分类编号不能为空";
                    return Task.FromResult(res);
                }
                if (string.IsNullOrWhiteSpace(request.ClassificationName))
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "工序分类名称不能为空";
                    return Task.FromResult(res);
                }
                if (request.Status != 0 && request.Status != 1)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "状态只能是0(禁用)或1(启用)";
                    return Task.FromResult(res);
                }

                // 检查存在
                var exists = repository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM ProcessClassification WHERE Id=@Id AND IsDeleted=0",
                    new { request.Id });
                if (exists == 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "记录不存在";
                    return Task.FromResult(res);
                }

                // 唯一性校验（排除自身）
                var dupCode = repository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM ProcessClassification WHERE ClassificationCode=@ClassificationCode AND Id<>@Id AND IsDeleted=0",
                    new { request.ClassificationCode, request.Id });
                if (dupCode > 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "工序分类编号已存在";
                    return Task.FromResult(res);
                }
                var dupName = repository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM ProcessClassification WHERE ClassificationName=@ClassificationName AND Id<>@Id AND IsDeleted=0",
                    new { request.ClassificationName, request.Id });
                if (dupName > 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "工序分类名称已存在";
                    return Task.FromResult(res);
                }

                var sql = @"UPDATE ProcessClassification
                            SET ClassificationCode=@ClassificationCode,
                                ClassificationName=@ClassificationName,
                                Sort=@Sort,
                                Status=@Status,
                                Remark=@Remark
                            WHERE Id=@Id AND IsDeleted=0";

                var rows = repository.Execute(sql, new
                {
                    request.ClassificationCode,
                    request.ClassificationName,
                    request.Sort,
                    request.Status,
                    request.Remark,
                    request.Id
                });

                if (rows <= 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "编辑失败";
                    return Task.FromResult(res);
                }

                res.Code = APIEnums.Success;
                res.Data = (int)request.Id;
                res.Msg = "编辑成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "编辑工序分类失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "编辑工序分类异常";
                res.Data = 0;
            }

            return Task.FromResult(res);
        }
    }
}
